from typing import List, Optional
from datetime import datetime
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from app.database import get_db
from app.models.log import Log
from app.models.user import User
from app.auth import get_current_active_user, get_current_admin

router = APIRouter()

@router.get("/", response_model=List[dict])
async def get_logs(
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=1000),
    user_id: Optional[int] = Query(None, description="用户ID筛选"),
    action: Optional[str] = Query(None, description="操作类型筛选"),
    start_date: Optional[datetime] = Query(None, description="开始日期"),
    end_date: Optional[datetime] = Query(None, description="结束日期"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_admin)
):
    """获取操作日志（管理员）"""
    query = db.query(Log)
    
    if user_id:
        query = query.filter(Log.user_id == user_id)
    
    if action:
        query = query.filter(Log.action == action)
    
    if start_date:
        query = query.filter(Log.created_at >= start_date)
    
    if end_date:
        query = query.filter(Log.created_at <= end_date)
    
    logs = query.order_by(Log.created_at.desc()).offset(skip).limit(limit).all()
    
    # 添加用户信息
    result = []
    for log in logs:
        user = db.query(User).filter(User.id == log.user_id).first()
        result.append({
            **log.__dict__,
            "user": {
                "id": user.id,
                "username": user.username,
                "full_name": user.full_name
            }
        })
    
    return result

@router.get("/my")
async def get_my_logs(
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=1000),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取当前用户的操作日志"""
    logs = db.query(Log).filter(Log.user_id == current_user.id).order_by(Log.created_at.desc()).offset(skip).limit(limit).all()
    return logs

@router.post("/")
async def create_log(
    action: str,
    description: str,
    exam_id: Optional[int] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """创建操作日志"""
    db_log = Log(
        user_id=current_user.id,
        exam_id=exam_id,
        action=action,
        description=description
    )
    db.add(db_log)
    db.commit()
    db.refresh(db_log)
    return db_log

@router.get("/stats/count")
async def get_log_stats(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_admin)
):
    """获取日志统计信息"""
    total = db.query(Log).count()
    today = db.query(Log).filter(func.date(Log.created_at) == func.current_date()).count()
    
    # 获取常见操作统计
    action_stats = db.query(
        Log.action,
        func.count(Log.id).label('count')
    ).group_by(Log.action).order_by(func.count(Log.id).desc()).limit(10).all()
    
    return {
        "total": total,
        "today": today,
        "actions": [{"action": item[0], "count": item[1]} for item in action_stats]
    }